import type { SiteBaseInfo } from '@/apis/model/site'
import {
  deleteApiSiteApi,
  getApiSiteDetailApi,
  updateApiSiteApi,
  updateApiSiteResolveStatusApi
} from '@/apis/modules/site/site'
import ContentContainer from '@/components/ContentContainer.vue'
import EditCname from '@/components/EditCname.vue'
import EditField from '@/components/EditField.vue'
import { Descriptions, Switch, type DescData } from '@arco-design/web-vue'
import IconsDelete from '~icons/icons/delete'
import IconsEdit from '~icons/icons/edit'
import IconsRefresh from '~icons/icons/refresh'
import IconsSuccess from '~icons/icons/success'
import IconsApplying from '~icons/icons/applying'
import IconsWarning from '~icons/icons/warning'
import useGroupArea from '../../hooks/useGroupArea'
import { Form, FormItem, Input, Button } from '@arco-design/web-vue'

export default defineComponent({
  setup() {
    const { visible, open } = usePopup()
    const router = useRouter()
    const route = useRoute()
    const { areaListOptions, siteGroupOptions } = useGroupArea()
    const id = computed(() => route.params.id as string)
    const baseInfo = ref<SiteBaseInfo>()
    const data = ref<DescData[]>([])
    const loading = ref(false)
    const accessLoading = ref(false)
    const getBaseInfo = () => {
      loading.value = true
      getApiSiteDetailApi({ id: id.value })
        .then((res) => {
          baseInfo.value = res
          setData(baseInfo.value)
        })
        .finally(() => {
          loading.value = false
        })
    }
    const updateBaseInfo = async (record: SiteBaseInfo) => {
      await updateApiSiteApi({ id: id.value, ...record })
      getBaseInfo()
    }

    const changeStatus = (record: SiteBaseInfo) => {
      return new Promise((resolve, reject) => {
        updateApiSiteApi({ id: id.value, ...record })
          .then(() => {
            baseInfo.value!.status = record.status === 1 ? 2 : 1
            resolve(void 0)
          })
          .finally(() => reject(false))
      })
    }
    const getResolveStatus = () => {
      accessLoading.value = true
      updateApiSiteResolveStatusApi({ id: id.value })
        .then((res) => {
          baseInfo.value!.resolve_info!.resolve_status = res.resolve_status
        })
        .finally(() => {
          accessLoading.value = false
        })
    }
    const deleteSite = () => {
      const nameVerification = reactive({ name: '' })
      const disabled = computed(
        () => nameVerification.name !== baseInfo.value?.domain
      )

      const loading = ref(false)
      const fn = () => {
        loading.value = true
        deleteApiSiteApi({ id: id.value })
          .then(() => {
            ToastUtils.success('操作成功')
            router.replace({ name: 'SiteList' })
            modalReturn.close()
          })
          .finally(() => {
            loading.value = false
          })
      }

      // CloudModal.error(
      //   {
      //     content: '确认删除此站点？',
      //     okText: '删除'
      //   },
      //   fn
      // )
      const modalReturn = CloudModal.error(
        {
          maskClosable: false,
          //content: text,
          okText: '确定',
          footer: () => {
            return (
              <div class="flex  justify-end">
                {/* <Button onClick={() => modalReturn.close()} class="mr-4">
                  取消
                </Button> */}
                <Button
                  status="danger"
                  disabled={disabled.value}
                  class={disabled.value ? 'bg-[#FBACA3]! w-full' : 'w-full'}
                  style={disabled.value ? 'border:1px solid #FBACA3' : ''}
                  onClick={() => fn()}
                  loading={loading.value}>
                  我已知晓后果并确认删除
                </Button>
              </div>
            )
          },
          content: () => (
            <div class="flex flex-col gap-y-6 text-1 w-full">
              <span class={`text-[#1D2129] `}>
                删除站点 “{baseInfo.value?.domain}”
                并清空所有数据，此操作无法撤销。
              </span>
              <div class="w-full">
                <Form layout="vertical" model={nameVerification}>
                  <FormItem
                    asteriskPosition="end"
                    field="name"
                    hide-asterisk
                    validateTrigger={'input'}
                  // rules={[
                  //   {
                  //     required: true,
                  //     validator(value, cb) {
                  //       if (!value) {
                  //         return cb('请输入提示内容')
                  //       }
                  //       if (value !== baseInfo.value?.domain) {
                  //         return cb('请输入提示内容')
                  //       }
                  //       return cb()
                  //     }
                  //   }
                  // ]}
                  >
                    {{
                      label: () => (
                        <span class="text-4">
                          请输入「
                          <span class={'text-red-500'}>
                            {baseInfo.value?.domain}
                          </span>
                          」确认
                        </span>
                      ),
                      default: () => (
                        <Input
                          class="w-full"
                          modelValue={nameVerification.name}
                          maxLength={64}
                          onInput={(v) => {
                            nameVerification.name = v
                          }}
                          placeholder=""></Input>
                      )
                    }}
                  </FormItem>
                </Form>
              </div>
            </div>
          )
        },
        fn
      )
    }
    const setData = (info: SiteBaseInfo) => {
      data.value = [
        {
          label: 'CNAME',
          value: () => (
            <div class="resolve-status">
              {info.resolve_info?.resolve_value}
              <IconsEdit class="refresh" onClick={open} />
            </div>
          ),
          span: 1
        },
        {
          label: '启用状态',
          value: () => (
            <div class="min-w-60">
              <Switch
                v-model={info.status}
                checked-value={1}
                unchecked-value={2}
                size="small"
                before-change={(v) => changeStatus({ status: v as 1 | 2 })}
              />
            </div>
          ),
          span: 1
        },
        {
          label: '接入状态',
          value: () => {
            return (
              <div class="resolve-status">
                {accessLoading.value
                  ? h(IconsApplying, { class: 'rotate-infinite' })
                  : info.resolve_info?.resolve_status === 1
                    ? h(IconsSuccess)
                    : h(IconsWarning)}
                {/* {info.resolve_info?.resolve_status === 1
                  ? h(IconsSuccess)
                  : h(IconsWarning)} */}
                {accessLoading.value
                  ? '检测中'
                  : info.resolve_info?.resolve_status === 1
                    ? '已接入'
                    : '未接入'}
                <IconsRefresh class="refresh" onClick={getResolveStatus} />
              </div>
            )
          },
          span: 1
        },
        {
          label: '分组',
          value: () => (
            <EditField
              edit-title="变更分组"
              defaultValue={info.group_info?.id}
              type="select"
              fn={updateBaseInfo}
              hide-asterisk
              field="group_id"
              placeholder="请选择分组"
              options={siteGroupOptions.value}
              label="选择分组"
              mouseOver
              content={info.group_info?.name}
            />
          ),
          span: 1
        },
        {
          label: '区域',
          value: () => (
            <section class="!w-80">
              <EditField
                edit-title="编辑区域"
                defaultValue={info.region_info?.id}
                type="select"
                field="region_id"
                hide-asterisk
                fn={updateBaseInfo}
                placeholder="请选择区域"
                label="选择区域"
                options={areaListOptions.value}
                mouseOver
                content={info.region_info?.name}
              />
            </section>
          ),
          span: 1
        },
        {
          label: '添加时间',
          value: formatUnix(info.created_at),
          span: 1
        },
        {
          label: '备注',
          value: () => (
            <div class="max-w-80">
              <EditField
                edit-title="编辑备注"
                defaultValue={info.remark}
                type="input"
                noVerification
                field="remark"
                hide-asterisk
                maxLength={20}
                fn={updateBaseInfo}
                placeholder="请输入备注"
                required={false}
                label="备注"
                mouseOver
                content={info.remark}
              />
            </div>
          ),
          span: 3
        }
      ]
    }

    watchEffect(() => {
      getBaseInfo()
    })
    return () => (
      <ContentContainer
        show-pagination={false}
        show-footer={false}
        loading={loading.value}
        refresh={false}
        inner
        class="site-base-info">
        {{
          header: () => (
            <div class="flex justify-between items-center w-full">
              <span class="text-2 text-lg font-bold">
                {baseInfo.value?.domain}
              </span>

              <a-link
                status="danger"
                class="flex gap-x-1 py-2! px-4!"
                onClick={deleteSite}>
                <IconsDelete />
                删除站点
              </a-link>
            </div>
          ),
          default: () => (
            <>
              <Descriptions data={data.value} class="!text-4 " />
              <EditCname
                modelValue={visible.value}
                siteBase={true}
                record={{
                  site_id: id.value,
                  siteName: baseInfo.value?.domain,
                  resolve_domain_id:
                    baseInfo.value?.resolve_info?.resolve_domain_id,
                  cname: baseInfo.value?.resolve_info?.resolve_name
                }}
                onReload={getBaseInfo}
                onUpdate:modelValue={(v) => {
                  visible.value = v
                }}></EditCname>
            </>
          )
        }}
      </ContentContainer>
    )
  }
})
